import { defineStore } from 'pinia'
// import { BookInfo } from './state'
import userApi from '@/api/userApi'
import { AxiosResponse } from 'axios'
import storage from '@/utils/goodStorageUtil'
import searchStore from '@/piniastore/search/index'
import { hasProps } from '../utils'

export default defineStore('userStore', {
  state: () => {
    return initState
  },
  getters: {
    storeLoginUser: (state) => {
      return hasProps(state.userinfo) ? state.userinfo : storage.get('loginUser')
    },
  },
  actions: {
    async login(username: string, psw: string) {
      const loginUser = { username, psw } as UserInfo
      const userInfo: AxiosResponse<UserInfo> = await userApi.login(loginUser)
      this.userinfo = userInfo.data
      storage.set('loginUser', userInfo.data)
      storage.set('token', userInfo.data.token)
    },
  },
})

const initState: InitUserState = {
  userinfo: {} as UserInfo,
}

type InitUserState = {
  userinfo: UserInfo
}
export type UserInfo = {
  userid: number
  token: string
  username: string
  psw: string
  address: string
  valid: number
}
